<?php
namespace Modules\Admin;

use Phalcon\DiInterface;
use Phalcon\Mvc\Dispatcher;

class Module implements \Phalcon\Mvc\ModuleDefinitionInterface {

  /**
     * Register a specific autoloader for the module
   *
   * @param DiInterface $di
     */
    public function registerAutoloaders(DiInterface $di = null) {
    (new \Phalcon\Loader()) -> registerNamespaces([
      'Assert'    => BASE_PATH . 'vendor/beberlei/assert/lib/Assert/',
      'Base64Url' => BASE_PATH . 'vendor/spomky-labs/base64url/src/',
      'Jose'      => BASE_PATH . 'vendor/spomky-labs/jose/src/',

      'Common'     => SRC_PATH . 'common/',
      'Components' => SRC_PATH . 'components/',

      __NAMESPACE__ . '\\Controllers' => __DIR__ . '/controllers/',
      __NAMESPACE__ . '\\Libraries'   => __DIR__ . '/libraries/',
      __NAMESPACE__ . '\\Services'    => __DIR__ . '/services/',
      __NAMESPACE__ . '\\Validations' => __DIR__ . '/validations/'
    ]) -> register();
  }

  /**
     * Register specific services for the module
   *
   * @param DiInterface $di
     */
    public function registerServices(DiInterface $di) {

    // Registering a dispatcher
    $di -> set('dispatcher', function() {
      $dispatcher = new \Phalcon\Mvc\Dispatcher();

      //$eventManager = new \Phalcon\Events\Manager();

      // Attach a event listener to the dispatcher (if any)
            // For example:
            // $eventManager->attach('dispatch', new \My\Awesome\Acl('frontend'));

      //$dispatcher -> setEventsManager($eventManager);
      $dispatcher -> setDefaultNamespace(__NAMESPACE__ . '\\Controllers');
      return $dispatcher;
    });

    $di -> set('backendCache', function() {
      $filename = BASE_PATH . 'runtime/cache/admin/';
      if(!is_dir($filename)) {
        mkdir($filename, 0777, true);
      }

      return new \Phalcon\Cache\Backend\File(
        \Phalcon\Cache\Frontend\Factory::load([
          'lifetime' => 86400,
          'adapter' => 'data'
        ]),
        [
          'cacheDir' => $filename
        ]
      );
    });

    // Set response and CORS
    $di -> get('response') -> setContentType('application/json', 'UTF-8');

    $di -> set('config', function() {
      return new \Phalcon\Config(require __DIR__ . '/config/config.php');
    });

    // Registering the view component
    $di -> set('view', function() {
      // Disables the auto-rendering process
      return (new \Phalcon\Mvc\View()) -> disable();
    });

    $di -> set('user', function() {
      return \Components\Account\Factory::load([
        'adapter' => 'User',
        'di' => \Phalcon\Di::getDefault()
      ]);
    }, false);
  }
}
?>